# -*- coding: utf-8 -*-

from os import path
from django.conf import settings
from django.http import HttpResponse
from django.http import Http404, HttpResponseRedirect, HttpResponseForbidden
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from django.contrib.auth.decorators import login_required

from models import WebComic, Strip
from forms import ComicStripForm, WebComicForm
import app_settings

DIRNAME = "comics"

# sends user to default webpage if no webcomics is registered
def require_webcomics():
    pass

def matureFilter(request):
    if request.GET.get('mature', False):
        request.session['mature']=True
    return request.session.get('mature', False)

@login_required
def status(request):
    "Returns the app instalation status"
    data = {
                   "DEFAULT_COMIC_BOOK set?":getattr(app_settings, "DEFAULT_COMIC_BOOK", False),
                   "At least one WebComic registered":WebComic.objects.count()>0}
    return render_to_response(path.join(DIRNAME, "status.html"), 
                              locals(), context_instance=RequestContext(request))
    
def index(request):
    """
    index is used to view all the avaiable comics. In case you just have one,
    you can change the url from this method to use django.generics redirect
    or change this method to render a opening page or something like it.
    """
    if WebComic.objects.count()==0 or getattr(app_settings, 'DEFAULT_COMIC_BOOK', False) is False:
        return HttpResponseRedirect( reverse("comics.status") )
    else: 
        webcomic = get_object_or_404(WebComic, pk=app_settings.DEFAULT_COMIC_BOOK)
        return HttpResponseRedirect(webcomic.link())

def strip(request, book_slug, strip_id, act=None):
    """
    Shows a comic strip
    """
    # use this if you have multiple webcomics in one site
    webcomics = WebComic.objects.all()    
    webcomic = get_object_or_404(WebComic, pk=book_slug)
    strips = webcomic.strips.all()    
    strip = get_object_or_404(Strip, pk=strip_id)
    owner = request.user == webcomic.owner # True if owner is accessing comic book
    
    # mudar para decorator
    is_mature = matureFilter(request)
    
    if webcomic.mature_content and not owner:
        if not is_mature:
            return render_to_response(path.join(DIRNAME, "mature_content.html"),
                                    locals(), context_instance=RequestContext(request))
    if act in ("edit", "del") and not owner:
        return HttpResponseForbidden(_("You do not have permission to do that unless you own this WebComic"))    
    
    if act=="edit":
        if request.POST:
            form = ComicStripForm(request.POST, request.FILES, instance=strip)
            if form.is_valid():
                strip = form.save()
                request.user.message_set.create(message="Strip '%s' edited." % strip.name)
                return HttpResponseRedirect(strip.link())
        else:
            form = ComicStripForm(instance=strip)
        form_legend = _("Editing comic %s") % strip.name
        return render_to_response(path.join(DIRNAME, "edit_comic.html"),
                                  locals(), context_instance=RequestContext(request))
        
    elif act=="del":
        strip.delete()
        request.user.message_set.create(message=_("Strip '%s' removed.") % strip.name)
        return HttpResponseRedirect(webcomic.link())
    
    image_width = min(strip.image.width, webcomic.max_comic_width)
    
    return render_to_response(path.join(DIRNAME, "comic.html"),
                              locals(), context_instance=RequestContext(request))

def webcomic(request, book_slug, act="current"):
    """
    valid act :
        current
        add
        last
        random
        first
        comment
        archieve
    """
    webcomic = get_object_or_404(WebComic, pk=book_slug)
    strips = webcomic.strips.all()
        
    # defining webcomic owner
    owner = request.user == webcomic.owner
    
    # everything that requires ownership should be filtered here
    if act in ("add", "configure") and not owner:
        return HttpResponseForbidden(_("You do not have permission to do that unless you own this WebComic"))
    
    if act=="add": # adding a comic book
        if request.POST:
            form = ComicStripForm(request.POST, request.FILES)
            if form.is_valid():
                instance = form.save(commit=False)
                instance.webcomic=webcomic
                instance.save()
                return HttpResponseRedirect(instance.link())
        else:
            form = ComicStripForm(initial={"webcomic":webcomic.slug})
                
            form_legend = _("Adding new Strip to %s") % webcomic.title.capitalize()
            return render_to_response(path.join(DIRNAME, "edit_comic.html"),
                            locals(), context_instance=RequestContext(request))
        
    if act=="configure": # configuring comic book        
        if request.POST:
            form = WebComicForm(request.POST, 
                                request.FILES, 
                                instance=webcomic)
            if form.is_valid():
                webcomic = form.save()
                request.user.message_set.create(message=_('Webcomic updated'))
                return HttpResponseRedirect(webcomic.link())
            
        else:
            form = WebComicForm(instance=webcomic)
        form_legend=_("Configuring Webcomic")
        return render_to_response(path.join(DIRNAME, "edit_comic.html"), 
                            locals(), context_instance=RequestContext(request))
    
    # if there are no strips avaiable, simple show the webcomic page 
    if strips.count()==0:
        return render_to_response(path.join(DIRNAME, "comic.html"),
                            locals(), context_instance=RequestContext(request))
        
    if act=="last" or act=="current":
        # gives back the last comic so far
        strip=webcomic.last_strip()
    elif act=="first":
        # gives back the first comic
        strip=webcomic.first_strip()
    elif act=="random":
        # gives back a random comic
        import random
        strip=strips.all()[random.randint(0, webcomic.strips.count()-1)]
    elif act=="archive":
        # shows a big archieve comic list. 100 comics per page
        page_number = request.GET.get('page', 1)
        page = Paginator(strips, 50).page(page_number)
        return render_to_response(path.join(DIRNAME, "archive.html"),
                          locals(), context_instance=RequestContext(request))
    
    return HttpResponseRedirect(strip.link())